package com.hui.servlet.classes;

import com.hui.entity.Class;
import com.hui.service.ClassService;
import com.hui.util.ServiceFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: 李昭辉
 * @Date: 2021/07/09/15:56
 * @Description: 添加与修改班级
 */
@WebServlet(name = "addAndUpdateClassServlet", urlPatterns = "/addAndUpdateClass")
public class AddAndUpdateClassServlet extends HttpServlet {
    private ClassService classService = ServiceFactory.getClassService();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        String className = req.getParameter("className");
        String grade = req.getParameter("grade");
        String teacher = req.getParameter("teacher");
        String slogan = req.getParameter("slogan");
        PrintWriter writer = resp.getWriter();
        // 如果有id那就是修改，没有的话就是添加
        if (id.equals("")) { // 添加操作
            Class aClass = new Class(0, className, grade, teacher, slogan, 0);
            boolean b = classService.addClass(aClass);
            if (b) {
                writer.write("<script>alert('添加成功!');window.location.href='classes'</script>");
            } else {
                writer.write("<script>alert('添加失败!!!');window.location.href='classes'</script>");
            }
        } else { // 修改操作
            Class aClass = new Class(Integer.parseInt(id), className, grade, teacher, slogan, 0);
            boolean b = classService.updateClass(aClass);
            if (b) {
                writer.write("<script>alert('修改成功!');window.location.href='classes'</script>");
            } else {
                writer.write("<script>alert('修改失败!!!');window.location.href='classes'</script>");
            }
        }
        writer.close();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}
